/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package contractmanager

import (
	"sync"

	"hundsun.com/hsl/hschain/common/config"

	"github.com/spf13/cobra"
)

var (
	contracts = make(map[string]*ContractRegisterItem)
	once      = &sync.Once{}
)

// Register Register Contract
func Register(contct *ContractRegisterItem) {
	if contct == nil {
		panic("contct param is nil")
	}
	name := contct.GetName()
	if len(name) == 0 {
		panic("contct name is empty")
	}
	if _, ok := contracts[name]; ok {
		panic("contct is existed name is " + name)
	}
	contracts[name] = contct
}

// AddContracts add Contracts
func AddContracts(mpcfg map[string]*config.PluginConfig) {
	once.Do(func() {
		for name, contct := range contracts {
			if v, ok := mpcfg[name]; ok {
				contct.AddContract(v)
			} else {
				contct.AddContract(nil)
			}
		}
	})
}

// AddCmd add Command for plugin
func AddCmd(rootCmd *cobra.Command) {
	for _, contct := range contracts {
		contct.AddCmd(rootCmd)
	}
}
